route.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { OpenaiPath } from "@/app/constant";
  2. import { prettyObject } from "@/app/utils/format";
  3. import { NextRequest, NextResponse } from "next/server";
  4. import { auth } from "../../auth";
  5. import { requestOpenai } from "../../common";
  6. const ALLOWD_PATH = new Set(Object.values(OpenaiPath));
  7. async function handle(
  8. req: NextRequest,
  9. { params }: { params: { path: string[] } },
  10. ) {
  11. console.log("[OpenAI Route] params ", params);
  12. const subpath = params.path.join("/");
  13. if (!ALLOWD_PATH.has(subpath)) {
  14. console.log("[OpenAI Route] forbidden path ", subpath);
  15. return NextResponse.json(
  16. {
  17. error: true,
  18. msg: "you are not allowed to request " + subpath,
  19. },
  20. {
  21. status: 403,
  22. },
  23. );
  24. }
  25. const authResult = auth(req);
  26. if (authResult.error) {
  27. return NextResponse.json(authResult, {
  28. status: 401,
  29. });
  30. }
  31. try {
  32. return await requestOpenai(req);
  33. } catch (e) {
  34. console.error("[OpenAI] ", e);
  35. return NextResponse.json(prettyObject(e));
  36. }
  37. }
  38. export const GET = handle;
  39. export const POST = handle;
  40. export const runtime = "edge";